﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using UnityEngine;


public enum NetEventType : short
{
    None,

    /// <summary>
    /// IP地址格式不正确
    /// </summary>
    COMM_IP_FORMAT_ERROR,
   
    /// <summary>
    /// Port格式不正确
    /// </summary>
    COMM_PORT_FOMMAT_ERROR,        
    /// <summary>
    /// Port范围不正确
    /// </summary>
    COMM_PORT_SCOPE_ERROR,

    /// <summary>
    /// 启动异步接收线程失败
    /// </summary>
    COMM_START_ASYNC_RECEIVE_THREAD_FAILED,

    /// <summary>
    /// 接收到消息
    /// </summary>
    COMM_RECEIVE_MESSAGE,

    /// <summary>
    /// 主动断开连接
    /// </summary>
    COMM_DISCONNECT_INITIATIVE,

    /// <summary>
    /// 网络异常，断开连接
    /// </summary>
    COMM_DISCONNECT_EXCEPTION,


    /// <summary>
    /// 服务器已经存在
    /// </summary>
    SS_SERVER_ALREADY_EXISTS,

    /// <summary>
    /// 服务器启动成功
    /// </summary>
    SS_SERVER_START_SUCCESS,

    /// <summary>
    /// 服务器启动失败
    /// </summary>
    SS_SERVER_START_FAILED,

    /// <summary>
    /// 服务器关闭
    /// </summary>
    SS_CLOSE_SERVER,

    /// <summary>
    /// 从客户端列表移除出错
    /// </summary>
    SS_REMOVE_CLIENT_FAILED,

    /// <summary>
    /// 客户端连接成功
    /// </summary>
    SS_CLIENT_CONNECT_SUCCESS,

    /// <summary>
    /// 客户端连接失败
    /// </summary>
    SS_CLIENT_CONNECT_FAILED,

    /// <summary>
    /// 开始连接服务器
    /// </summary>
    SC_BEGIN_CONNECT,

    /// <summary>
    /// 连接超时
    /// </summary>
    SC_CONNECT_TIMEOUT,

    /// <summary>
    /// 连接服务器异常
    /// </summary>
    SC_CONNECT_EXCEPTION,

    /// <summary>
    /// 连接服务器成功
    /// </summary>
    SC_CONNECT_SUCCESS,

}

public struct CoreEvent
{
    public NetEventType eventType;
    /// <summary>
    /// 消息数据
    /// </summary>
    public byte[] data;
    public string log;
    public ClientBase sender;
}

public class NetCore
{
    //客户端
    public const int CONN_BEGIN_CONNECT = 0;
    public const int CONN_IP_ERROR = 1;
    public const int CONN_PORT_ERROR = 2;
    public const int CONN_FAILD = 3;
    public const int CONN_SUCCESS = 6;

    public const int MSG_SERVER_CLOSE = 11;
    public const int MSG_RECEIVE_EXCEPTION = 12;
    public const int MSG_CREATE_RECEIVE_THREAD_FAILD = 13;
    public const int MSG_RECEIVE_SUCCESS = 14;

    //服务器
    public const int CREATE_SERVER_IP_ERROR = 21;
    public const int CREATE_SERVER_PORT_ERROR = 22;
    public const int CREATE_SERVER_FAILD = 23;
    public const int CREATE_SERVER_SUCCESS = 24;

    public const int ACCEPT_USER_SUCCESS = 6;
    public const int ACCEPT_USER_FAILD = 7;

    public const int CLIENT_DISCONNECT_INITIATIVE = 8;
    public const int CLIENT_DISCONNECT_EXCEPTION = 9;

    private static Regex rgx = new Regex(@"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");

    private static event Action<CoreEvent> addCoreEvent;

    public static void InitNetCore(Action<CoreEvent> ace)
    {
        //if (addCoreEvent == null)
        //{
            addCoreEvent += ace;
            //Debug.Log("Event Register Success:" + (addCoreEvent != null));
        //}
        //else
        //{
        //    throw new Exception("addCoreEvent 多次赋值，发生冲突");
        //}
    }

    public static void AddEvent(CoreEvent ce)
    {
        if (addCoreEvent != null)
        {
            addCoreEvent(ce);
            
        }
        else
        {
            throw new Exception("使用AddEvent前请先执行InitNetCore方法");
        }
       
    }
    public static void ResetNetCore(Action<CoreEvent> ace)
    {
        if (addCoreEvent != null)
        {
            addCoreEvent -= ace;
            //Debug.Log("Event Cancel Success:" + (addCoreEvent != null));
        }
       
    }

    /// <summary>
    /// 验证IP地址和port
    /// </summary>
    /// <param name="ep"></param>
    /// <returns></returns>
    public static bool VerifyEndPoint(string ip, string port, ref EndPoint ep, ref CoreEvent ce)
    {
        if (!rgx.IsMatch(ip.Trim()))
        {
            ce.eventType = NetEventType.COMM_IP_FORMAT_ERROR;
            return false;
        }

        int s_port = 0;
        if (!int.TryParse(port, out s_port))
        {
            ce.eventType = NetEventType.COMM_PORT_FOMMAT_ERROR;
            return false;
        }
        if (s_port >= 65536 || s_port <= 1024)
        {
            //Debug.LogError("端口请使用1024~65536之间的任意数值");
            ce.eventType = NetEventType.COMM_PORT_SCOPE_ERROR;
            ce.log = "端口请使用1024~65536之间的任意数值";
            return false;
        }
        ce.eventType = NetEventType.None;
        ep = new IPEndPoint(IPAddress.Parse(ip.Trim()), s_port);
        return true;
    }

    public static void Log(object log)
    {
        Debug.Log(log);
    }
    public static void LogWarning(object log)
    {
        Debug.LogWarning(log);
    }
    public static void LogError(object log)
    {
        Debug.LogError(log);
    }
}